package com.Servlet;

import com.DAO.DaoImpl.UserDaoImpl;
import com.DAO.UserDao;
import com.entity.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理 GET 请求，可以重定向到一个适当的页面或者返回相应的 HTML 内容
        response.sendRedirect(request.getContextPath() + "/showUsers.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userIdStr = request.getParameter("id");
        String username = request.getParameter("username");
        String email = request.getParameter("email");

        // 检查 id 是否为空
        if (userIdStr != null && !userIdStr.isEmpty()) {
            try {
                int id = Integer.parseInt(userIdStr);

                // 检查用户名和邮箱是否为空
                if (username != null && !username.isEmpty() && email != null && !email.isEmpty()) {
                    // 创建用户对象
                    User user = new User();
                    user.setId(id);
                    user.setUsername(username);
                    user.setEmail(email);

                    // 更新用户信息
                    userDao.updateUser(user);
                    response.sendRedirect(request.getContextPath() + "/");
                } else {
                    // 如果用户名或邮箱为空，转发到错误页面
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
                    dispatcher.forward(request, response);
                }
            } catch (NumberFormatException e) {
                // 如果无法解析 id 为整数，转发到错误页面
                RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
                dispatcher.forward(request, response);
            }
        } else {
            // 如果 id 为空，转发到错误页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
            dispatcher.forward(request, response);
        }
    }
}
